package com.yunqian.web;

import com.aliyun.oss.OSSClient;
import com.yunqian.exception.ActionException;
import com.yunqian.util.AliyunUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

/**
 * @author zou
 * @describe
 * @date 2018/10/25
 */

@Controller
@RequestMapping("/fileUpload/oss/")
@Log4j2
public class AliyunController {

    /**
     * 上传文件
     *
     * @param request
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String key = null;
        if (!file.isEmpty()) {
            try {
                // 创建OSSClient实例。
                OSSClient ossClient = AliyunUtil.getOSSClient();
                key = System.currentTimeMillis() + "_" + file.getOriginalFilename().replaceAll(" ", "");
                // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
                ossClient.putObject(AliyunUtil.BUCKET_NAME, key, new ByteArrayInputStream(file.getBytes()));
                // 关闭OSSClient。
                ossClient.shutdown();
                return key;
            } catch (IOException e) {
                e.printStackTrace();
                throw new ActionException("上传出错，请重试");
            }
        }
        return key;
    }

    /**
     * 删除文件
     *
     * @param modifyData 要删除文件的key
     * @return
     */
    @PutMapping("/delete")
    @ResponseBody
    public void deleteFile(@RequestBody Map<String, Object> modifyData) {
        OSSClient ossClient = AliyunUtil.getOSSClient();
        ossClient.deleteObject(AliyunUtil.BUCKET_NAME, String.valueOf(modifyData.get("key")));
        // 关闭OSSClient。
        ossClient.shutdown();
    }


}
